// pages/signIn/signIn.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    signIn:true,//查询当天是否已经签到，flag为false:已经签到过,true:今天未签到过
    count:'',//总积分数
    dateData: [],
    isSignin: false,
    week: ['日','一','二','三','四','五','六'],
    month:'',   //当前月
    continueSign:false,   //当天的签到是否是连续签到
    signIncount:'',   // 签到应该加多少积分
    signId:'',      //签到的ID
    movesuccessShow:false,    //已经签到过弹出提示框
    qiandao:'',       //返回给后台的连续签到或签到的汉字
    signedmonthList:[]    //当月签到的列表
  },



// 关闭移动文件夹成功的弹框
onClosemovesuccess(){
  this.setData({ movesuccessShow: false });
},



    // 签到过程：
    // 1.查询当前用户的总积分数
    // 2.查询当天用户是否已经签到过
    // 3、点击签到（分为连续签到和不连续签到两种加分）
    // 4、查询是否是连续签到
    // 5、 查看积分规则
    // 6、调接口添加积分


  // 1  查询当前用户的总积分数  
  integral:function(){
    var that = this
    wx.request({
      url: getApp().globalData.baseUrl +'/wago/jifen/findById',
      data: {
        userid:getApp().globalData.openid
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      success: function(res){
        // success
        if(res.data){
          that.setData({
            count:res.data.data.zongjifen
          })
        }
        
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },
  // 2  查询当天用户是否已经签到过
  addCurrentDay:function(){
    console.log('666666666666666')
    var that = this
    
    wx.request({
      url: getApp().globalData.baseUrl + '/wago/qiandao/findCurrentDay',
      headers:{
        'content-type': 'application/x-www-form-urlencoded '
      },
      data: {
        userid:getApp().globalData.openid
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function(res){
        // success   flag为false:已经签到过,true:今天未签到过
        if(res.data.flag){
          //未签到
          that.setData({
            signIn:true
          })
        }else{
          //已经签到过
          that.setData({
            signIn:false
          })
          that.todaystyle()
        }
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },
  // 3 点击 签到
  signIn:function(){
    console.log('44444444444444444444444444')
    var that = this;
    // 判断用户是否已经登录
    console.log('getApp().globalData.openid',getApp().globalData.openid)
    if(getApp().globalData.openid == undefined){   //用户还没有登录
      wx.showToast({
        title: '请先登录！',
        icon:'none'
      })

    }else{   //已经登录过的
      if(that.data.signIn){    //未签到过
        console.log('that.data.signIn',that.data.signIn)
        wx.request({
          url: getApp().globalData.baseUrl + '/wago/qiandao/addCurrentDay',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            userid:getApp().globalData.openid
          },
          method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          // header: {}, // 设置请求的 header
          success: function(res){
            // success
            if(res.data.flag){
              // 修改今天已经签到的日历样式
              that.todaystyle()
              that.setData({
                signIn:false,//已经签到
              })
              // 签到成功后调用接口查看今天的签到是否是连续签到
              that.continueSigned();
              
            }
            
          },
          fail: function() {
            // fail
          },
          complete: function() {
            // complete
          }
        })
      }else{//已经签到过
        that.setData({
          movesuccessShow:true
        })
      }
    }
    // console.log('qiandao',that.data.signIn)
    
    
  },
  // 4、查询当天是否是连续签到
  continueSigned:function(){
    var that = this;
    that.getcurrentmonth()   //查询当月签到
    wx.request({
      url: getApp().globalData.baseUrl + '/wago/qiandao/isContinuous',
      data: {
        userid:getApp().globalData.openid
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function(res){
        // success
        console.log('查询当天是否是连续签到',res.data.flag)
        that.setData({
          continueSign:res.data.flag
        })
        that.findJifenControl()   //查看积分规则
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },
  //5  积分规则
  findJifenControl:function(){
    var that = this
    var signId = ''
    if(that.data.continueSign){   //2：签到   3：连续签到  continueSign：false签到  true连续签到
        signId = '3'
    }else{
      signId = '2'
    }
    console.log('signId',signId)
    wx.request({
      url: getApp().globalData.baseUrl + '/wago/jifen/findJifenControl',
      data: {
        id:signId
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function(res){
        // success
        console.log('res积分规则',res)
        that.setData({
          signIncount:res.data.data.changejifen,  //积分数
          qiandao:res.data.data.name    //积分的名字
        })
        that.signCount()   //返回给后台签到的积分数
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },
  // 6  返回给后台签到的积分数(分为连续签到和不连续签到)
  signCount:function(){
    var that = this
    var timestamp=new Date().getTime()
    console.log('timestamp',timestamp)
    wx.request({
      url: getApp().globalData.baseUrl +'/wago/jifen/changeJifen',
      data: {
        userid:getApp().globalData.openid,
        changejifen:that.data.signIncount,
        changename:that.data.qiandao,
        changetime:timestamp
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function(res){
        // success
        console.log('签到添加积分',res)
        that.integral()   //再次查询总积分数
        
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },

  // 修改当天的样式
  todaystyle:function(){
    console.log('签到')
    var that = this;
    
    var date = new Date();
    var d = date.getDate();   //获取当天的日期
    var oldArr =  that.data.dateData.filter(item =>{
      return item.type == 'curr'
    })
    for(var j = 0;j < oldArr.length;j++){
      if(oldArr[j].type == 'curr' && oldArr[j].dot == 'checked'){
        console.log('asdasdasdasd',oldArr[j])
        for(var i = 0;i < that.data.dateData.length;i++){
           if(that.data.dateData[i].type == 'curr' && that.data.dateData[i].day == d){
            that.data.dateData[i].today = 'today'
            console.log(that.data.dateData[i])
           }
        };
      }
    }
    that.setData({
      dateData:that.data.dateData
    })
    
  },

  // 查询当前月签到
  getcurrentmonth:function(){
    var that = this
    var date = new Date();
    var d = date.getDate();   //获取当天的日期
    // 查询当月签到
    wx.request({
      url: getApp().globalData.baseUrl +'/wago/qiandao/findCurrentMonth',
      data: {
        userid:getApp().globalData.openid
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function(res){
        // success
        that.setData({
          signedmonthList:res.data.data
        })
        var oldArr = that.data.dateData.filter(item =>{
          return item.type == 'curr'
        })
        for(let i = 0;i<oldArr.length;i++){
          for(let j=0;j<that.data.signedmonthList.length;j++){
            if(oldArr[i].day == that.data.signedmonthList[j]){
              oldArr[i].dot = 'checked'
            }
          }
        };
       
       for(var j = 0;j < oldArr.length;j++){
            if(oldArr[j].type == 'curr' && oldArr[j].dot == 'checked'){
              for(var i = 0;i < that.data.dateData.length;i++){

                 if(that.data.dateData[i].type == 'curr' && oldArr[j].day  == that.data.dateData[i].day){
                  that.data.dateData[i] = oldArr[j]
                 }

                 if(that.data.dateData[i].type == 'curr' && that.data.dateData[i].day == d){
                  that.data.dateData[i].today = 'today'
                 }
              };
            }
        }
       
        that.setData({
          dateData:that.data.dateData
        })
        
        
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },
  /**
  * year string 年  如:2020 
  * month string 月 如: 5
  * return array 所有天数 如:[1,2,3...,31]
  **/
 monthDays(year,month){ 
    let days_count = new Date(year,month,0).getDate() //月总天数 如:31
    let days = []; //存放月的天数
    for(let i = 1; i <= days_count; i++)
    days.push(i)
    return days;
  },
  //初始化当月数据
  initCurrMonthData(){
    let currDate = new Date(); //当前日期
    let currMonthDays =  this.monthDays(currDate.getFullYear(),currDate.getMonth() + 1) //当月 +1是因为月从0开始  只有0-11
    let lastMonthDays = this.monthDays(currDate.getFullYear(),currDate.getMonth() ) //上个月
    let currFirstWeek = new Date(currDate.getFullYear(),currDate.getMonth() - 1, 1).getDay() + 1;   //这个月的1号是星期几  -1是因从0开始 
    //月最后一天是星期几
    this.setData({
      month:currDate.getMonth()+1
    })
    let dateData = [];
    dateData = currMonthDays.map(val => this.formatDay(val)) //当月的数据

    for(let i = 0; i < currFirstWeek; i++)  //上月要显示的
    dateData.unshift(
      this.formatDay( lastMonthDays.pop(),'last')
    );

    let nextLenth = 42 - dateData.length;  // 42是因为 6 * 7格式
    for(var i = 1; i <= nextLenth; i++) //下个月需要显示的日期
    dateData.push(
        this.formatDay( i, 'next')
    );

    this.setData({
      dateData : dateData
    })

    this.getcurrentmonth()   //查询当前月签到

  },
  formatDay(day,type = 'curr'){ //日期数据的格式化
  return {day:day,type:type};
  },

  onShareAppMessage: function () {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initCurrMonthData()   //初始化当月数据
    
    this.integral()     //查询当前用户的总积分

    this.addCurrentDay()   //查看当天是否签到

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

})